import {createStore} from 'vuex'

// 创建一个新的store实例
const store = createStore({
    state() {
        return {
            username:"ryann",
            count: 0,
            foodInCart: [],
            //存储账户信息
            account:localStorage.getItem('account')?localStorage.getItem('account'):null,
            //存储登录的token
            token:localStorage.getItem('token')?localStorage.getItem('token'):null
        }
    },
    mutations: {
        increment (state) {
            state.count++
        },
        SET_FOOD_IN_CART(state, cartItems) {
            state.foodInCart = cartItems; // 更新状态的 mutation
        },
        //登录成功后设置account
        setAccount(state,account){
            state.account=JSON.stringify(account)
            localStorage.setItem('account',JSON.stringify(account))
        },
        //登录后保存token
        setToken(state,token){
            localStorage.setItem('token',token)
            state.token=token
        },
        //退出后删除token和account
        logout(state){
            localStorage.removeItem('token')
            state.token=null
            localStorage.removeItem('account')
            state.account=null
        }
    },
    actions: {
        updateFoodInCart({ commit }, cartItems) {
          commit('SET_FOOD_IN_CART', cartItems); // 触发 mutation 更新状态的 action
        },
      }
})

export default store